/**
 * Created by Administrator on 2016/8/30.
 * 定时任务
 */
BaisonTaskMdl.factory('Task', ['$rootScope', '$q', 'apiService', 'timeStamp2String', 'dbTrans', 'dbUpdate', 'dbDelete', 'dbInsert', 'dbSelect', 'dbReplaceInto', 'dbReplace', 'dbUpdateAdd', 'dbInsertMulti', 'PatchList', 'dbExec', 'PatchInstall',function ($rootScope, $q, apiService, timeStamp2String, dbTrans, dbUpdate, dbDelete, dbInsert, dbSelect, dbReplaceInto, dbReplace, dbUpdateAdd, dbInsertMulti, PatchList, dbExec, PatchInstall) {
    //获取自动下载数据
    var get_sys_task = function () {
        var sql = 'select * from sys_task where off_or_on= 1 and status=1';
        return dbSelect('YsPos', sql);
    };
    //读取要执行的定时任务
    var get_task_name = function () {
        var sql = 'select * from sys_task';
        return dbSelect('YsPos', sql);
    };
    //修改本地定时任务的同步状态和频率
    var update_task_status = function (data) {
        var insert_data = [];
        $.each(data, function (i, n) {
            var time;
            switch (n.frequency) {
                case 1:
                    time = 1800;
                    break;
                case 2:
                    time = 3600;
                    break;
                case 3:
                    time = 21600;
                    break;
                case 4:
                    time = 43200;
                    break;
                case 5:
                    time = 86400;
                    break;
                default:
                    time = 3600;
                    break;
            }
            var param = {};
            param.off_or_on = n.off_or_on;
            param.frequency = time;
            param.start_time = n.start_time; //* 1 + 365 * 10 * 24 * 3600 * 1000;
            param.end_time = n.end_time;// * 1 + 365 * 10 * 24 * 3600 * 1000;
            insert_data[n.code] = dbUpdate('sys_task', param, {
                'code': n.code
            });
        });
        return $q.all(insert_data);
    };
    //定时任务主表信息更新+++++++++++++++++++++++++++++++++++++
    var update_status_by_sys_task = function (data) {
        //console.log('模型层参数',data);
        var param = {};
        param.status = data.status;
        param.update_time = data.update_time;
        return dbUpdate('sys_task', param, {
            'code': data.code
        });
    };

    //获取shop数据
    var get_shop_data = function () {
        var data = {'distributor_type': 1, 'fields': 'distributor_code,distributor_name,area_code,brand_code,rebate,use_pd,use_tk'};
        return apiService('base/shop/get_list',data);
    }

    //下载基础数据
    var download_base_data = function () {
        var deferred = $q.defer();
        var promose = deferred.promise;
        get_shop_data().then(function (response) {
           console.log(response);
           if(response.data.status == 1){
               var insert_data = [];
               $.each(response.data.data.data, function (i, n) {
                   insert_data.push({
                       ShopCode: n.distributor_code,
                       ShopName: n.distributor_name,
                       AreaCode: n.area_code,
                       BrandCode: n.brand_code,
                       Id: n.distributor_code,
                       ShopRebate :n.rebate, //商店折扣
                       UsePd:n.use_pd,
                       UseTk:n.use_tk
                   });
               });
               return dbTrans.begin().then(function (success) {
                   return  dbReplaceInto('PosShop', insert_data, ['ShopCode', 'ShopName', 'AreaCode', 'BrandCode', 'Id', 'ShopRebate','UsePd','UseTk']);
               }).then(function (success) {
                   return dbTrans.commit().then(function () {
                       deferred.resolve('success');
                       insert_data.forEach(function (e,i) {
                           if(e.ShopCode == $rootScope.current_shop.ShopCode){
                               $rootScope.current_shop = e;
                           }
                       })
                       return $q.when();
                   });
               }).catch(function (err) {
                   return dbTrans.rollback();
               });
           }else{
               baison_app.api.toast({msg: '没有商品数据'});
               deferred.resolve('error');
           }
        });
        return promose.then(function () {
            baison_app.api.toast({msg: '下载安装完成'});
            return $q.when();
        });

    };

    //获取上次下载促销时间戳
    var get_last_down_goods_time = function () {
        var sql = "select update_time from sys_task where off_or_on= 1 and status=1 and code = 'task_020' ";
        return dbSelect('YsPos', sql);
    };
    //获取goods数据
    var get_goods_data = function (param) {
        return apiService('base/goods/get_list', param);
    };
    //获取goods数据
    var get_skus_data = function (param) {
        return apiService('base/goods/get_sku_list', param);
    };
    //下载商品sku数据
    var download_goods_data = function () {
        //下载商品资料 sku
        var per_size = 100;//   每页数量
        var page = 1;//默认第一页 第几页
        var page_count = 0;
        var lastchanged = 0;//上次获取商品的时间
        var goods_data = {};//商品 json数据
        var skus_data = {}; //sku json 数据

        //获取上次下载促销时间戳
        return get_last_down_goods_time().then(function (ret) {

            var deferredgood = $q.defer();
            var promisegood = deferredgood.promise;
            var deferredsku = $q.defer();
            var promisesku = deferredsku.promise;
            var goods_install = [];
            if (ret.length > 0) {
                lastchanged = ret[0].update_time;
            }
            var exist_get_skus = function (i) {
                page = i;
                var param = {
                    'page': page,
                    'per_size': per_size,
                    'lastchanged': lastchanged
                };
                get_skus_data(param).then(function (response) {
                    console.log(response);
                    if (response.data.status == 1) {
                        page_count = response.data.data.page_count;
                        skus_data = response.data.data.data;
                        skus_data = JSON.stringify(skus_data);

                        PatchInstall(skus_data, 'sku', '', '').then(function (msg) {
                            i++;
                            if (page_count >= i) {
                                exist_get_skus(i);
                            } else {
                                if (i != 1) {
                                    //baison_app.api.toast({msg: '下载安装完成'});
                                    deferredsku.resolve('success');
                                } else {
                                    //baison_app.api.toast({msg: '没有最新促销数据'});
                                    deferredsku.resolve('error');
                                }
                            }

                        });

                    } else {
                        if (i != 1) {
                            //baison_app.api.toast({msg: '下载安装完成'});
                            deferredsku.resolve('success');
                        } else {
                            //baison_app.api.toast({msg: '没有最新促销数据'});
                            deferredsku.resolve('error');
                        }
                        return;
                    }
                });
            };
            exist_get_skus(1);
            goods_install['skus']= promisesku;
            //执行获取促销数据
            var exist_get_goods = function (i) {
                page = i;
                var param = {
                    'page': page,
                    'per_size': per_size,
                    'lastchanged': lastchanged
                };
                get_goods_data(param).then(function (response) {
                    console.log(response);
                    if (response.data.status == 1) {
                        page_count = response.data.data.page_count;
                        goods_data = response.data.data.data;
                        goods_data = JSON.stringify(goods_data);

                        PatchInstall(goods_data, 'skufile', '', '').then(function (msg) {
                            i++;
                            if (page_count >= i) {
                                exist_get_goods(i);
                            } else {
                                if (i != 1) {
                                    //baison_app.api.toast({msg: '下载安装完成'});
                                    deferredgood.resolve('success');
                                } else {
                                    //baison_app.api.toast({msg: '没有最新促销数据'});
                                    deferredgood.resolve('error');
                                }
                            }

                        });

                    } else {
                        if (i != 1) {
                            //baison_app.api.toast({msg: '下载安装完成'});
                            deferredgood.resolve('success');
                        } else {
                            //baison_app.api.toast({msg: '没有最新促销数据'});
                            deferredgood.resolve('error');
                        }
                        return;
                    }
                });
            };
            exist_get_goods(1);
            goods_install['goods'] = promisegood;
            return $q.all(goods_install).then(function(){
                baison_app.api.toast({msg: '下载安装完成'});
                return $q.when();
            });

        });
    };



    return {
            get_task_name:get_task_name,
            update_task_status:update_task_status,
            update_status_by_sys_task:update_status_by_sys_task,
            download_goods_data: download_goods_data,
            download_base_data: download_base_data,
            get_sys_task:get_sys_task
        };

}]);
